package org.jeecgframework.tinydao.factory;

import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.tinydao.annotation.TinyDao;
import org.jeecgframework.tinydao.util.TinyDaoUtil;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;



/** 
* @ClassName: TinyDaoBeanFactory 
* @Description: 初始化TinyBean
* @author zx zx2009428@163.com
* @date 2015年3月21日 下午4:29:07 
*  
*/
public class TinyDaoBeanFactory implements BeanFactoryPostProcessor{

	private static final Logger logger = Logger.getLogger(TinyDaoBeanFactory.class);
	
	//TinDao 扫描路径
	private List<String> packagesToScan;
	@Override
	public void postProcessBeanFactory(
			ConfigurableListableBeanFactory beanFactory) throws BeansException {
		logger.debug("........TinyDaoBeanFactory..........更新资源...........开始");
		try{
		//循环传入的TinyDao配置
		for(String pac :packagesToScan){
			if(StringUtils.isNotEmpty(pac)){
				Set<Class<?>> classSet = PackagesToScanUtil.getClasses(pac);
				for(Class tinyDaoClass:classSet){
					if(tinyDaoClass.isAnnotationPresent(TinyDao.class)){
						//单独加载一个接口的代理类
						ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
						proxyFactoryBean.setBeanFactory(beanFactory);
						proxyFactoryBean.setInterfaces(new Class[]{tinyDaoClass});
						proxyFactoryBean.setInterceptorNames(new String[]{"tinyDaoHandler"});
						String beanName = TinyDaoUtil.getFirstSmall(tinyDaoClass.getSimpleName());
						if(!beanFactory.containsBean(beanName)){
							logger.info("TinyDao Interface[/"+tinyDaoClass.getName()+"/] onto Spring bean '"+beanName+"'" );
							beanFactory.registerSingleton(beanName, proxyFactoryBean.getObject());
						}
					}
				}
				}
			
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		logger.debug("................TinyDaoBeanFactory................ContextRefreshed................end...................");
	}
	

}
